package com.heaboy.emaidemo1.util;

import com.heaboy.emaidemo1.config.MailInfo;
import com.heaboy.emaidemo1.config.MailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.List;
import java.util.Properties;

@Component
public class MailSenderUtil {

    @Autowired
    private MailProperties mailProperties;

    // 根据邮箱类型获取配置（默认使用default-type）
    private MailProperties.MailConfig getMailConfig(String mailType) {
        // 确定使用的邮箱类型（未指定则用默认）
        String useType = (mailType == null) ? mailProperties.getDefaultType() : mailType;
        // 获取对应配置
        MailProperties.MailConfig config = mailProperties.getConfigs().get(useType);
        if (config == null) {
            throw new RuntimeException("未配置 [" + useType + "] 类型的邮箱参数");
        }
        return config;
    }

    // 构建MailInfo（根据邮箱类型）
    private MailInfo getMailInfo(String mailType) {
        MailProperties.MailConfig config = getMailConfig(mailType);
        MailInfo mailInfo = new MailInfo();
        mailInfo.setMailServerHost(config.getSmtp().getHost());
        mailInfo.setMailServerPort(String.valueOf(config.getSmtp().getPort()));
        mailInfo.setUserName(config.getSender().getUsername());
        mailInfo.setPassword(config.getSender().getPassword());
        mailInfo.setValidate(config.getSmtp().isAuth());
        mailInfo.setDebugMode(true);
        return mailInfo;
    }

    // 获取邮件会话（支持多邮箱）
    public Session getMailSession(String mailType) {
        MailInfo mailInfo = getMailInfo(mailType);
        Properties properties = mailInfo.getProperties();
        // 补充SSL配置
        MailProperties.MailConfig config = getMailConfig(mailType);
        properties.setProperty("mail.smtp.ssl.enable", String.valueOf(config.getSmtp().isSslEnable()));
        properties.setProperty("mail.smtp.socketFactory.class", config.getSmtp().getSocketFactoryClass());
        properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(config.getSmtp().getSocketFactoryPort()));
        return Session.getDefaultInstance(properties, mailInfo.getAuthenticator());
    }

    /**
     * 单个发送（支持指定邮箱类型）
     * @param mailType 邮箱类型："qq" 或 "163"（null则用默认）
     */
    public void sendMailTOSingleUser(String toEmail, String title, String content, String mailType) {
        MailProperties.MailConfig config = getMailConfig(mailType);
        // 处理空值（优先用传入的title，否则用配置的默认主题）
        String finalTitle = (title == null || title.trim().isEmpty()) ? config.getDefaults().getTitle() : title;
        String finalContent = (content == null || content.trim().isEmpty()) ? config.getDefaults().getContent() : content;

        Session session = getMailSession(mailType);
        try {
            MimeMessage message = new MimeMessage(session);
            // 发件人（使用当前邮箱类型的配置）
            message.setFrom(new InternetAddress(
                    config.getSender().getUsername(),
                    config.getSender().getName(),
                    "UTF-8"
            ));
            // 收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            // 抄送自己
            message.setRecipient(Message.RecipientType.CC, new InternetAddress(config.getSender().getUsername()));
            // 主题和内容（使用处理后的非空值）
            message.setSubject(MimeUtility.encodeText(finalTitle, "UTF-8", "B"));
            message.setContent(finalContent, "text/html;charset=UTF-8");

            Transport.send(message);
            System.out.println("使用 [" + (mailType == null ? mailProperties.getDefaultType() : mailType) + "] 邮箱发送成功！");
        } catch (Exception e) {
            System.err.println("发送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 重载：使用默认邮箱发送
    public void sendMailTOSingleUser(String toEmail, String title, String content) {
        sendMailTOSingleUser(toEmail, title, content, null);
    }

    /**
     * 群发邮件（支持指定邮箱类型）
     */
    public void sendMailToUserArray(List<String> toEmails, String title, String content, String mailType) {
        MailProperties.MailConfig config = getMailConfig(mailType);
        String finalTitle = (title == null) ? config.getDefaults().getTitle() : title;
        String finalContent = (content == null) ? config.getDefaults().getContent() : content;

        Session session = getMailSession(mailType);
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getSender().getUsername(), config.getSender().getName(), "UTF-8"));

            // 批量设置收件人
            if (toEmails != null && !toEmails.isEmpty()) {
                Address[] recipients = new InternetAddress[toEmails.size()];
                for (int i = 0; i < toEmails.size(); i++) {
                    recipients[i] = new InternetAddress(toEmails.get(i));
                }
                message.setRecipients(Message.RecipientType.TO, recipients);
            }

            message.setRecipient(Message.RecipientType.CC, new InternetAddress(config.getSender().getUsername()));
            message.setSubject(MimeUtility.encodeText(finalTitle, "UTF-8", "B"));
            message.setContent(finalContent, "text/html;charset=UTF-8");

            Transport.send(message);
            System.out.println("使用 [" + (mailType == null ? mailProperties.getDefaultType() : mailType) + "] 邮箱群发成功！");
        } catch (Exception e) {
            System.err.println("群发失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 重载：使用默认邮箱群发
    public void sendMailToUserArray(List<String> toEmails, String title, String content) {
        sendMailToUserArray(toEmails, title, content, null);
    }
}
